package cn.xyafu.lost.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import cn.xyafu.lost.R;
import cn.xyafu.lost.pojo.User;
import cn.xyafu.lost.utils.LostOpenHelper;
import cn.xyafu.lost.utils.ResponseEntityToModule;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class Login extends AppCompatActivity {

    private static EditText edt_name;
    private static EditText edt_pwd;
    private static CheckBox checkBox;
    private static Button btn_login;
    private static TextView tv_register;

    private static EditText register_name;
    private static EditText register_password;
    private static Button btn_register;

    public String editTextName = "";
    public String editTextPwd = "";
    public SharedPreferences sp = null;

    int isRemember = 0; // 0：默认不记住密码  1：记住密码

    LostOpenHelper openHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initView();

        openHelper = new LostOpenHelper(Login.this,"lostdb",null,1);
        // 上次登录记住密码，初始化数据
        initData();
        // 登录
        btn_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toLogin(v);
            }
        });

        tv_register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toRegister(v);
            }
        });

    }

    // 初始化页面组件
    private void initView(){
        edt_name = findViewById(R.id.edt_name);
        edt_pwd = findViewById(R.id.edt_pwd);
        checkBox = findViewById(R.id.checkbox);
        btn_login = findViewById(R.id.btn_login);
        tv_register = findViewById(R.id.tv_register);

    }

    // 获取数据库中存储的用户数据，自动填充到文本框中
    private boolean initData(){
        SQLiteDatabase db = openHelper.getReadableDatabase();
        Cursor cursor = db.rawQuery("select * from t_user", null);
        cursor.moveToFirst();	//移至第一行
        for(int i = 0; i < cursor.getCount(); i++){	//遍历每行数据
            // 获取列数据
            String unikename =  cursor.getString(1);
            String password = cursor.getString(2);
            isRemember = cursor.getInt(3);
            if (unikename == null && password == null){
                return false;
            }
            if (isRemember == 1){
                edt_name.setText(unikename);
                edt_pwd.setText(password);
                checkBox.setChecked(true);
            }
        }
        return true;

    }

    private void toLogin(View view){
        // 获取数据
        editTextName = edt_name.getText().toString().trim();
        editTextPwd = edt_pwd.getText().toString().trim();
        // 在callable中使用intent跳转页面
        final Login that = this;
        //  发起网络请求
        // (1). 创建OkHttpCLient对象
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(5, TimeUnit.SECONDS);
        builder.readTimeout(5, TimeUnit.SECONDS);
        builder.writeTimeout(5, TimeUnit.SECONDS);
        OkHttpClient client = builder.build();
        // (2). 创建Request对象
        Request request = new Request.Builder().url(
                "http://localhost/Lost_ssm/android/login?unikename="+ editTextName +"&upassword=" + editTextPwd
                ).get().build();
        // (3). 创建Call对象
        Call call = client.newCall(request);
        // (4). 将请求添加到队列中
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println("请求失败");
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                System.out.println("请求成功");
                // 将json数据转化为model数据
                User user = (User) ResponseEntityToModule.parseJsonToModule(response.body().string(), User.class);
                String id = String.valueOf(user.getUid());
                if (user != null){
                    // 登录成功
                    // 选择记住密码，则保存数据到数据库
                    SQLiteDatabase db = openHelper.getWritableDatabase();
                    db.execSQL("insert into t_user values(0,?,?,0,?,?,?);", new String[]{editTextName,editTextPwd,user.getUsex(),user.getUemail(),id});
                    if (checkBox.isChecked()){
                        db.execSQL("update t_user set id=?,unikename=?,upassword=?,remember=1;",new String[]{id,editTextName, editTextPwd});
                        db.close();
                    }else {
                        db.execSQL("update t_user set id=?, unikename=?,upassword=?,remember=0;",new String[]{id,editTextName, editTextPwd});
                        db.close();
                    }

                    Intent intent =new Intent(that, MainActivity.class);
                    startActivityForResult(intent,0);
                    // 登陆完成后直接结束页面
                    that.finish();
                } else {
                    edt_name.post(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(that, "用户名或密码不正确", Toast.LENGTH_SHORT).show();
                        }
                    });
                }

            }
        });

    }

    private void toRegister(View v){

        LayoutInflater inflater = LayoutInflater.from(Login.this);
        View textEntryView = inflater.inflate(R.layout.dialog_register, null);
        register_name = textEntryView.findViewById(R.id.register_name);
        register_password = textEntryView.findViewById(R.id.register_password);
        btn_register = textEntryView.findViewById(R.id.btn_register);

        AlertDialog.Builder builder = new AlertDialog.Builder(Login.this);
        builder.setTitle("注册");
        builder.setView(textEntryView);
        final Dialog dialog =  builder.show();

        btn_register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //  发起网络请求
                // (1). 创建OkHttpCLient对象
                OkHttpClient.Builder builder = new OkHttpClient.Builder();
                builder.connectTimeout(5, TimeUnit.SECONDS);
                builder.readTimeout(5, TimeUnit.SECONDS);
                builder.writeTimeout(5, TimeUnit.SECONDS);
                OkHttpClient client = builder.build();
                // (2). 创建Request对象
                Request request = new Request.Builder().url(
                        "http://localhost/Lost_ssm/android/register?unikename="+ register_name.getText().toString().trim() +"&upassword=" + register_password.getText().toString().trim()
                ).get().build();
                // (3). 创建Call对象
                Call call = client.newCall(request);
                // (4). 将请求添加到队列中
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        System.out.println("请求失败");
                        e.printStackTrace();
                    }
                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        System.out.println("请求成功");
                        // 将json数据转化为model数据
                        Boolean flag = Boolean.parseBoolean(response.body().string());
                        if (flag){
                            // 注册成功
                            edt_name.post(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(Login.this, "注册成功，请登录", Toast.LENGTH_SHORT).show();
                                }
                            });
                            dialog.dismiss();
                        } else {
                            edt_name.post(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(Login.this, "注册失败，请稍后重试", Toast.LENGTH_SHORT).show();
                                }
                            });
                        }
                    }
                });

            }
        });

    }

}
